package com.yuxiang.flowable.exception;

import com.yuxiang.flowable.result.BaseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * @author : yx-0176
 * @description
 * @date : 2022/3/9
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {


    /**
     * 参数绑定异常
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = BindException.class)
    @ResponseBody
    public BaseResult bindingExceptionHandler(HttpServletRequest req, BindException e) {
        String url = req.getRequestURI();
        BindingResult bindingResult = e.getBindingResult();
        log.warn("发生请求参数绑定异常！原因是：{}", e);
        return handleBindResult(url, bindingResult);
    }

    /**
     * 参数校验异常
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public BaseResult argNotValidExceptionHandler(HttpServletRequest req, MethodArgumentNotValidException e) {
        String url = req.getRequestURI();
        BindingResult bindingResult = e.getBindingResult();
        log.warn("发生请求参数校验异常！原因是：{}", e);
        return handleBindResult(url, bindingResult);
    }

    /**
     * 参数校验异常2
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = IllegalArgumentException.class)
    @ResponseBody
    public BaseResult argIllegalExceptionHandler(HttpServletRequest req, IllegalArgumentException e) {
        String url = req.getRequestURI();
        log.warn("发生请求参数校验异常！原因是：{}", e);
        return BaseResult.buildFailure(500, e.getMessage());
    }


    /**
     * 其他异常
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public BaseResult databaseExceptionHandler(HttpServletRequest req, Exception e) {
        log.error("发生系统异常！原因是：{}", e);
        return BaseResult.buildFailure(500, e.getMessage());
    }

    private BaseResult handleBindResult(String url, BindingResult bindingResult) {
        ObjectError objectError = bindingResult.getAllErrors().get(0);
        String errMsg = objectError.getDefaultMessage();
        String errCode = objectError.getCode();
        log.info("请求参数异常, request url = {}, request param = {}, error code = {}, error message = {}",
                url, errCode, errMsg);
        return BaseResult.buildFailure(500, errMsg);
    }
}
